<template>
  <div style="max-width: 800px; margin: 40px auto;">
    <el-card shadow="hover">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span style="font-size: 20px; font-weight: bold;">收货地址</span>
          <el-button type="primary" @click="showAddDialog = true">
            <i class="el-icon-plus"></i> 新增地址
          </el-button>
        </div>
      </template>
      
      <!-- 地址列表 -->
      <div v-if="addressList.length === 0" style="text-align: center; padding: 40px; color: #999;">
        暂无收货地址，请添加您的收货地址
      </div>
      
      <div v-else>
        <div v-for="address in addressList" :key="address.addressId" class="address-item">
          <div class="address-content">
            <div class="address-info">
              <div class="receiver">
                <span class="name">{{ address.receiverName }}</span>
                <span class="phone">{{ address.phone }}</span>
                <el-tag v-if="address.isDefault === 1" type="success" size="small">默认</el-tag>
              </div>
              <div class="address-detail">
                {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detailAddress }}
              </div>
            </div>
            <div class="address-actions">
              <el-button v-if="address.isDefault !== 1" type="text" @click="setDefaultAddress(address.addressId)">
                设为默认
              </el-button>
              <el-button type="text" @click="editAddress(address)">编辑</el-button>
              <el-button type="text" style="color: #f56c6c;" @click="deleteAddress(address.addressId)">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑地址弹窗 -->
    <el-dialog 
      v-model="showAddDialog" 
      :title="editingAddress ? '编辑地址' : '新增地址'" 
      width="500px"
    >
      <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="80px">
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="addressForm.receiverName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addressForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-input v-model="addressForm.province" placeholder="请输入省份" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="addressForm.city" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="区县" prop="district">
          <el-input v-model="addressForm.district" placeholder="请输入区县" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input 
            v-model="addressForm.detailAddress" 
            type="textarea" 
            :rows="3"
            placeholder="请输入详细地址" 
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault" @change="onDefaultCheckboxChange">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAddress">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserAddresses, addUserAddress, updateUserAddress, deleteUserAddress, setDefaultUserAddress } from '@/utils/request'
import { useUserStore } from '@/stores/userStore'

const addressList = ref([])
const showAddDialog = ref(false)
const editingAddress = ref(null)
const addressFormRef = ref()
const userStore = useUserStore()

const addressForm = reactive({
  addressId: null,
  receiverName: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: '',
  isDefault: false
})

const addressRules = {
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度2-20位', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' }
  ],
  district: [
    { required: true, message: '请输入区县', trigger: 'blur' }
  ],
  detailAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '详细地址长度5-100位', trigger: 'blur' }
  ]
}

// 获取地址列表
async function fetchAddressList() {
  try {
    const res = await getUserAddresses()
    if (res.success) {
      addressList.value = res.data || []
    } else {
      ElMessage.error(res.message || '获取地址列表失败')
    }
  } catch (e) {
    ElMessage.error('获取地址列表失败')
  }
}

// 编辑地址
function editAddress(address) {
  editingAddress.value = address
  Object.assign(addressForm, {
    addressId: address.addressId,
    receiverName: address.receiverName,
    phone: address.phone,
    province: address.province,
    city: address.city,
    district: address.district,
    detailAddress: address.detailAddress,
    isDefault: address.isDefault === 1
  })
  showAddDialog.value = true
}

// 保存地址
async function saveAddress() {
  addressFormRef.value.validate(async valid => {
    if (valid) {
      try {
        const data = {
          ...addressForm,
          isDefault: addressForm.isDefault ? 1 : 0
        }
        
        let res
        if (editingAddress.value) {
          res = await updateUserAddress(data)
        } else {
          res = await addUserAddress(data)
        }
        
        if (res.success) {
          ElMessage.success(editingAddress.value ? '修改成功' : '添加成功')
          showAddDialog.value = false
          resetForm()
          fetchAddressList()
        } else {
          ElMessage.error(res.message || '操作失败')
        }
      } catch (e) {
        ElMessage.error('操作失败')
      }
    }
  })
}

// 删除地址
async function deleteAddress(addressId) {
  try {
    await ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
      type: 'warning'
    })
    
    const res = await deleteUserAddress(addressId)
    if (res.success) {
      ElMessage.success('删除成功')
      fetchAddressList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 设置默认地址
async function setDefaultAddress(addressId) {
  try {
    const res = await setDefaultUserAddress(addressId)
    if (res.success) {
      ElMessage.success('设置成功')
      fetchAddressList()
    } else {
      ElMessage.error(res.message || '设置失败')
    }
  } catch (e) {
    ElMessage.error('设置失败')
  }
}

// 重置表单
function resetForm() {
  editingAddress.value = null
  Object.assign(addressForm, {
    addressId: null,
    receiverName: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detailAddress: '',
    isDefault: false
  })
}

// 监听弹窗关闭
function handleDialogClose() {
  resetForm()
}

function onDefaultCheckboxChange(val) {
  if (val && addressList.value.some(addr => addr.isDefault === 1 && addr.addressId !== addressForm.addressId)) {
    ElMessageBox.confirm(
      '每个用户只能有一个默认地址，设置新默认地址会自动取消原有默认地址，是否继续？',
      '提示',
      { type: 'warning' }
    ).catch(() => {
      addressForm.isDefault = false; // 用户取消则还原
    });
  }
}

onMounted(() => {
  fetchAddressList()
})
</script>

<style scoped>
.address-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 16px;
  padding: 16px;
  transition: all 0.3s;
}

.address-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.address-info {
  flex: 1;
}

.receiver {
  margin-bottom: 8px;
}

.receiver .name {
  font-weight: bold;
  margin-right: 12px;
}

.receiver .phone {
  color: #666;
  margin-right: 12px;
}

.address-detail {
  color: #333;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  gap: 8px;
}
</style> 